package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.BottleNetTypeTable;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.domain.BottleNetTypeEntry;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class ChooseBottleActivity extends BasicActivity implements BasicUIEvent, Callback {

	private final int init_bottle_info = 1;
	private final int init_permission_error = 4;
	
	private final int net_choose_location = 2;
	private final int bttype_choose_location = 3;
	private final int init_location = 5;
	private final int gain_bottle_success = 6;
	private final int gain_bottle_error = 7;
	private final int gain_bottle = 8;
	
	private List<BottleTypeEntry> bottltTypes;
	private List<BottleNetTypeEntry> bottleNetTypes;
	private List<BottlePermission> permissions;
	
	private GridView gridView;
	private ImageView back;
	
	LinearLayout bottle_description;
	TextView bottle_desc;
	TextView bottle_provision;
	Button button;
	PopupWindow pop;
	
	private BottleTypeAdapter typeAdapter;
	private BottleNetTypeAdapter netAdapter;
	private String type;
	private int netLocationSelect;
	private int bttypeLocationSelect;
	private int bottleId;
	
	private Handler handler;
	private ImageLoader loader;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.choose_bottle);
		type = getIntent().getStringExtra("type");
		loader = new ImageLoader(this, AppContext.BottleTimelineIcon);
		initWidget();
		initPopuwindow();
		//网络定位
		networkLocat();
		UICore.eventTask(this, this, init_bottle_info, getString(R.string.init_data), null);
	}	
	private void initWidget() {
		if (type.equals("throw")) {
			((TextView)findViewById(R.id.topbar_title)).setText(TextUtil.R("bottle_txt_title_throw"));
		} else {
			((TextView)findViewById(R.id.topbar_title)).setText(TextUtil.R("bottle_txt_title_gain"));
		}
		gridView = (GridView) findViewById(R.id.choose_bottle_grid);
		back = (ImageView) findViewById(R.id.topbar_back);
		back.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ChooseBottleActivity.this.finish();
			}
		});
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> convertView, View view, int position, long id) {
				if (type.equals("throw")) {
					initBottleTypeDescription(position);
				} else {
					initBottleNetTypeDescription(position);
				}
				if (pop.isShowing()) {
					pop.dismiss();
				} else {
					pop.showAtLocation(view, Gravity.CENTER, 0, 0);
				}
			}
		});
	}
	
	private void initPopuwindow() {
		View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_popuwindow, null);
		bottle_desc = (TextView) view.findViewById(R.id.choose_bottle_desc);
		bottle_provision = (TextView) view.findViewById(R.id.choose_bottle_provision);
		button = (Button) view.findViewById(R.id.choose_bottle_button);
		bottle_description = (LinearLayout) view.findViewById(R.id.choose_bottle_description);
		pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		pop.setAnimationStyle(R.style.AnimationPreview);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
	}
	
	private void initBottleNetTypeDescription(int position) {
		try {
			final BottleNetTypeEntry entry = bottleNetTypes.get(position);
			if (entry == null) {
				return;
			}
			bottleId = entry.getNettypeid();
			netLocationSelect = entry.getNettype_location_select();
			button.setText(ChooseBottleActivity.this.getString(R.string.choose_bchoose_try));
			button.setBackgroundResource(R.drawable.btn_red_try);
			final BottlePermission permission = getPermission(entry.getNettypeid());
			if (permission != null) {
				if (permission.enable == 0) {
					button.setBackgroundResource(R.drawable.btn_gray_try);
				} else {
					button.setBackgroundResource(R.drawable.btn_red_try);
				}
			}
			if (AppContext.language == 1) {
				bottle_desc.setText(entry.getNettype_desc_cn());
			} else {
				bottle_desc.setText(entry.getNettype_desc_en());
			}
			bottle_provision.setText(permission.useterm);
			button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (permission != null) {
						if (permission.enable == 0) {
							onToast(permission.reason);
							return;
						}
					} 
					pop.dismiss();
					chooseLocationTab(net_choose_location, netLocationSelect);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void initBottleTypeDescription(int position) {
		try {
			final BottleTypeEntry entry = bottltTypes.get(position);
			if (entry == null) {
				return;
			}
			bottleId = entry.getBttypeid();
			bttypeLocationSelect = entry.getBttype_location_select();
			button.setText(ChooseBottleActivity.this.getString(R.string.choose_bottle_throw));
			button.setBackgroundResource(R.drawable.btn_blue_try);
			final BottlePermission permission = getPermission(entry.getBttypeid());
			if (permission != null) {
				if (permission.enable == 0) {
					button.setBackgroundResource(R.drawable.btn_gray_try);
				} else {
					button.setBackgroundResource(R.drawable.btn_blue_try);
				}
			}
			if (AppContext.language == 1) {
				bottle_desc.setText(entry.getBttype_desc_cn());
			} else {
				bottle_desc.setText(entry.getBttype_desc_en());
			}
			bottle_provision.setText(permission.useterm);
			button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (permission != null) {
						if (permission.enable == 0) {
							onToast(permission.reason);
							return;
						}
					} 
					pop.dismiss();
					chooseLocationTab(bttype_choose_location, bttypeLocationSelect);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void chooseLocationTab(int locatoinType, int locationSelect) {
		try {
			if (locationSelect > 0) {
				String choices[] = new String[2];
				if (locatoinType == net_choose_location) {
					choices[0] = getString(R.string.choose_location_here_try);
					choices[1] = getString(R.string.choose_location_search_try);
				} else {
					choices[0] = getString(R.string.choose_location_here_throw);
					choices[1] = getString(R.string.choose_location_search_throw);
				}
				chooseAction(choices, locatoinType);
			} else {
				String choices[] = new String[1];
				if (locatoinType == net_choose_location) {
					choices[0] = getString(R.string.choose_location_here_try);
				} else {
					choices[0] = getString(R.string.choose_location_here_throw);
				}
				chooseAction(choices, locatoinType);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void doSelectChooseEvent(int which, int chooseType) {
		if (chooseType == net_choose_location) {
			if (which == 0) {
				UICore.eventTask(this, this, gain_bottle, "", null);
			} else {
				Intent intent = new Intent(ChooseBottleActivity.this, ChooseLocationTabsActivity.class);
				intent.putExtra("type", type);
				intent.putExtra("bottleId", bottleId);
				intent.putExtra("locationSelect", netLocationSelect);
				startActivity(intent);
			}
		} else {
			if (which == 0) {
				UICore.eventTask(this, this, init_location, "", null);
			} else {
				Intent intent = new Intent(ChooseBottleActivity.this, ChooseLocationTabsActivity.class);
				intent.putExtra("type", type);
				intent.putExtra("bottleId", bottleId);
				intent.putExtra("locationSelect", bttypeLocationSelect);
				startActivity(intent);
			}
		}
	}
	
	private void gainBottle() {
		String url = UrlConfig.gain_bt;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("nettypeid", String.valueOf(bottleId));
		paramsMap.put("bt_geo_lng", String.valueOf(AppContext.getInstance().getLongitude() == 0.0 ? 0 : AppContext.getInstance().getLongitude()));
		paramsMap.put("bt_geo_lat", String.valueOf(AppContext.getInstance().getLatitude() == 0.0 ? 0 : AppContext.getInstance().getLatitude()));
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			JSONObject obj = new JSONObject(result);
			JSONObject resultObj = obj.getJSONObject("results");
			int success = resultObj.getInt("success");
			if (success == 1) {
				String successmsg = resultObj.getString("successmsg");
				int gainbt_type = resultObj.getInt("gainbt_type");
				String gainbt_msg = resultObj.getString("gainbt_msg");
				Object[] objs = new Object[3];
				objs[0] = successmsg;
				objs[1] = gainbt_type;
				objs[2] = gainbt_msg;
				Message msg = Message.obtain(handler, gain_bottle_success, objs);
				handler.sendMessage(msg);
			} else {
				String errmsg = resultObj.getString("errmsg");
				Message msg = Message.obtain(handler, gain_bottle_error, errmsg);
				handler.sendMessage(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_bottle_info:
			initBottleInfo();
			handler.sendEmptyMessage(init_bottle_info);
			break;
		case init_permission_error:
			onToast((String) obj);
			break;
		case init_location:
			handler.sendEmptyMessage(init_location);
			break;
		case gain_bottle:
			gainBottle();
			break;
		default:
			break;
		}
	}
	
	private void initBottleInfo() {
		if (type.equals("throw")) {
			BottleTypeTable btt = new BottleTypeTable();
			bottltTypes = btt.getBottleTypes();
			getThrowBottlePermission();
		} else {
			BottleNetTypeTable bntt = new BottleNetTypeTable();
			bottleNetTypes = bntt.getBottleNetTypes();
			getTryBottlePermission();
		}
	}
	
	private void getThrowBottlePermission() {
		String url = UrlConfig.get_sendbt_priv;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int authok = resultObj.getInt("authok");
				if (authok == 0) {
					String errmsg = resultObj.getString("errmsg");
					Message msg = Message.obtain(handler, init_permission_error, errmsg);
					handler.sendMessage(msg);
				} else {
					if (obj.has("sendbt_privs_list")) {
						JSONArray arrays = obj.getJSONArray("sendbt_privs_list");
						permissions = new ArrayList<ChooseBottleActivity.BottlePermission>();
						for (int i = 0;i < arrays.length();i++) {
							BottlePermission permission = new BottlePermission();
							JSONObject priobj = arrays.getJSONObject(i);
							permission.bottleId = priobj.getInt("bttypeid");
							permission.enable = priobj.getInt("enable");
							permission.reason = priobj.getString("reason");
							permission.useterm = priobj.getString("bttype_useterm");
							permissions.add(permission);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private BottlePermission getPermission(int bottleId) {
		if (permissions != null && !permissions.isEmpty()) {
			for (BottlePermission permission : permissions) {
				if (permission.bottleId == bottleId) {
					return permission;
				}
			}
		}
		return null;
	}
	
	private void getTryBottlePermission() {
		String url = UrlConfig.get_usenet_priv;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int authok = resultObj.getInt("authok");
				if (authok == 0) {
					String errmsg = resultObj.getString("errmsg");
					Message msg = Message.obtain(handler, init_permission_error, errmsg);
					handler.sendMessage(msg);
				} else {
					if (obj.has("usenet_privs_list")) {
						JSONArray arrays = obj.getJSONArray("usenet_privs_list");
						permissions = new ArrayList<ChooseBottleActivity.BottlePermission>();
						for (int i = 0;i < arrays.length();i++) {
							BottlePermission permission = new BottlePermission();
							JSONObject priobj = arrays.getJSONObject(i);
							permission.bottleId = priobj.getInt("nettypeid");
							permission.enable = priobj.getInt("enable");
							permission.reason = priobj.getString("reason");
							permission.useterm = priobj.getString("nettype_useterm");
							permissions.add(permission);
						}
					}
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public class BottleTypeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return bottltTypes == null ? 0 : bottltTypes.size();
		}

		@Override
		public Object getItem(int position) {
			return bottltTypes == null ? null : bottltTypes.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder holder;
			if (convertView != null) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				holder = new ViewHolder();
				view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_griditem, null);
				holder.bottle_icon = (ImageView) view.findViewById(R.id.choose_bottle_bottle_icon);
				holder.bottle_name = (TextView) view.findViewById(R.id.choose_bottle_bottle_name);
				view.setTag(holder);
			}
			BottleTypeEntry entry = bottltTypes.get(position);
			if (entry != null) {
				loader.DisplayImage(entry.getBttype_sjwicon(), holder.bottle_icon, R.drawable.bottle_type_1);
				if (AppContext.language == 1) {
					holder.bottle_name.setText(entry.getBttype_name_cn());
				} else {
					holder.bottle_name.setText(entry.getBttype_name_en());
				}
			}
			return view;
		}
	}
	
	
	public class BottleNetTypeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return bottleNetTypes == null ? 0 : bottleNetTypes.size();
		}

		@Override
		public Object getItem(int position) {
			return bottleNetTypes == null ? null : bottleNetTypes.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder holder;
			if (convertView != null) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				holder = new ViewHolder();
				view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_griditem, null);
				holder.bottle_icon = (ImageView) view.findViewById(R.id.choose_bottle_bottle_icon);
				holder.bottle_name = (TextView) view.findViewById(R.id.choose_bottle_bottle_name);
				view.setTag(holder);
			}
			BottleNetTypeEntry entry = bottleNetTypes.get(position);
			if (entry != null) {
				loader.DisplayImage(entry.getNettype_sjwicon(), holder.bottle_icon, R.drawable.bottle_type_1);
				if (AppContext.language == 1) {
					holder.bottle_name.setText(entry.getNettype_name_cn());
				} else {
					holder.bottle_name.setText(entry.getNettype_name_en());
				}
			}
			return view;
		}
		
	}
	
	
	public static class ViewHolder {
		ImageView bottle_icon;
		TextView bottle_name;
	}
	
	public class BottlePermission {
		int bottleId;
		int enable;
		String reason;
		String useterm;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (pop.isShowing()) {
				pop.dismiss();
				return true;
			}
		} 
		return super.onKeyDown(keyCode, event);
	}
	
	

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_bottle_info:
			if (type.equals("throw")) {
				typeAdapter = new BottleTypeAdapter();
				gridView.setAdapter(typeAdapter);
			} else {
				netAdapter = new BottleNetTypeAdapter();
				gridView.setAdapter(netAdapter);
			}
			break;
		case init_location:
			if (type.equals("throw")) {
				Intent intent2 = new Intent(ChooseBottleActivity.this, ThrowBottleSettingActivity.class);
				intent2.putExtra("bttype_id", bottleId);
				intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude());
				intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude());
				startActivity(intent2);
			} 
			break;
		case gain_bottle_error:
			onToast((String) msg.obj);
			break;
		case gain_bottle_success:
			try {
				Object[] objs = (Object[]) msg.obj;
				onToast((String) objs[0]);
				Intent intent = new Intent(ChooseBottleActivity.this, BottleTipsActivity.class);
				intent.putExtra("type", "try");
				intent.putExtra("bottleId", Integer.parseInt(objs[1].toString()));
				intent.putExtra("gainbt_msg", objs[2].toString());
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		return false;
	}
}
